package cn.shiwei.controller;

import cn.shiwie.domain.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 订单接口
 * @author 1363732197
 */
@RestController
// @DefaultProperties(defaultFallback = "FallbackMethod") // 给这个类统一配置熔断, 托底方法
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/getById/{id}")
    @HystrixCommand(fallbackMethod = "getByIdFallback") // 指定降级方法
    public User getById(@PathVariable("id") Long id){
        // 远程调用
        String url = "http://USER-SERVER/getById/" + id;
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }

    // 降级方法, 参数和返回值和被溶度的方法一直, 方法名和@HystrixCommand(fallbackMethod = "getByIdFallback")中fallbackMethod的值一致
    public User getByIdFallback(@PathVariable("id") Long id){
        return new User(-1L, "出现异常", "服务出错");
    }

    // 托底方法, 公共的托底方法不应该有参数, 返回类型和被熔断的方法返回值类型兼容
    public User FallbackMethod(){
        return new User(-1L, "出现异常", "服务出错");
    }
}
